﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace StockTradTest.Data
{
    public class GetInvestor
    {
        public static Investor GetInvestorData(int date)
        {
            return BuildData(GetInvestorByDate(date),date);
        }
        private static string GetInvestorByDate(int date)
        {

            try
            {
                var data = MakeData(date);
                string _url = "http://www.chinaclear.cn/cms-search/monthview.action?action=china";
                var request = (HttpWebRequest)WebRequest.Create(_url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                //request.ContentType = "application/json";
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
                request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:85.0) Gecko/20100101 Firefox/85.0";

                request.KeepAlive = true;
                //请求流
                request.ContentLength = data.Length;
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(data, 0, data.Length);
                    requestStream.Close();
                
                    HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
                    System.IO.Stream stream = resp.GetResponseStream();
                    //获取响应内容
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(stream, System.Text.Encoding.UTF8))
                    {
                        string temp = StripHtml(reader.ReadToEnd());
                        return temp;
                    }
                }
            }
            catch(Exception e)
            {
                Console.Write(e);
            }
            return null;
        }
        private class dataStream
        {
            public string key;
            public string value;
            public dataStream(string _key,string _value)
            {
                key = _key;
                value = _value;
            }
        }
        private static byte[] MakeData(int date)
        {
            string year, month;
            string temp = date.ToString();
            year = temp.Substring(0, 4);
            month = temp.Substring(4, 2);
            string dateStr = string.Format("{0}%E5%B9%B4{1}%E6%9C%88", year, month);

            List<dataStream> data = new List<dataStream>();
            data.Add(new dataStream("riqi", dateStr));
            data.Add(new dataStream("channelFidStr", "e990411f19544e46be84333c25b63de6"));
            data.Add(new dataStream("channelIdStr", "bd095cc08f744c089b159a3bb744b9d0"));
            System.Text.StringBuilder builder = new System.Text.StringBuilder();
            int i = 0;
            foreach (var item in data)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.key, item.value);
                i++;
            }
            return Encoding.UTF8.GetBytes(builder.ToString());
        }
        private static string StripHtml(string strhtml)
        {
            
            int cutStart = strhtml.IndexOf("月份");
            if (cutStart == -1) return null;
            int cutEnd = strhtml.IndexOf("注");
            //Console.Write(cutStart.ToString() + cutEnd.ToString());
            string stroutput = strhtml.Substring(cutStart, cutEnd - cutStart);
            stroutput = new Regex(@"<[^>]+>|</[^>]+>").Replace(stroutput, "");
            stroutput = new Regex(@"(&nbsp;)+").Replace(stroutput, "");
            stroutput = new Regex(@"(&ensp;)+").Replace(stroutput, "");
            stroutput = stroutput.Replace(",", "");
            stroutput = new Regex(@"市\s{1,}值", RegexOptions.IgnoreCase).Replace(stroutput, "市值");
            stroutput = new Regex(@"[(（]", RegexOptions.IgnoreCase).Replace(stroutput, "");
            stroutput = new Regex(@"[)）]", RegexOptions.IgnoreCase).Replace(stroutput, "");
            stroutput = new Regex(@"万元|万笔|万户|亿元|万\s{1,}户|亿\s{1,}元|只|万|个", RegexOptions.IgnoreCase).Replace(stroutput, "");
            stroutput = new Regex(@"\s{1,}", RegexOptions.IgnoreCase).Replace(stroutput, ",").Trim();
            stroutput = stroutput.Replace(",流通市值,", ",");
            stroutput = stroutput.Replace("期末有效账,户数", "期末有效账户数");
            stroutput = stroutput.Replace("登记存管证券,总", "登记存管证券总");
            stroutput = stroutput.Replace("登记存管证,", "登记存管证");
            //Console.WriteLine(stroutput);
            return stroutput;
        }

        private static Investor BuildData(string input, int date)
        {
            if (input == null) return null;
            string[] inputArray = input.Split(',');
            Investor investor = new Investor();
            investor.Date = date;
            int step = 3;
            if(date<201101)
            {
                step = 2;
            }
            for (int i = 0;i <inputArray.Length; i+=step)
            {
                //if (i >= inputArray.Length) break;
                switch(inputArray[i])
                {
                    case "月份":break;
                    case "新增开户数": investor.newInvestors = double.Parse(inputArray[i + 1]); break;
                    case "新开股票账户数": investor.newInvestors = double.Parse(inputArray[i + 1]); break;
                    case "新增投资者数": investor.newInvestors = double.Parse(inputArray[i + 1]); break;
                    case "期末账户数": investor.aliveInvestors = double.Parse(inputArray[i + 1]); break;
                    case "期末股票账户数": investor.aliveInvestors = double.Parse(inputArray[i + 1]); break;
                    case "期末有效账户数": investor.aliveInvestors = double.Parse(inputArray[i + 1]); break;
                    case "期末投资者数": investor.aliveInvestors = double.Parse(inputArray[i + 1]); break;
                    case "登记存管证券数": investor.stockNumber = double.Parse(inputArray[i + 1]); break;
                    case "登记存管证券总面值": investor.stockPrice = double.Parse(inputArray[i + 1]); break;
                    case "登记存管证券总市值": investor.stockMarketPrice = double.Parse(inputArray[i + 1]); break;
                    case "登记存管流通市值": investor.OnSellPrice = double.Parse(inputArray[i + 1]); break;
                    case "非限售市值": investor.OnSellPrice = double.Parse(inputArray[i + 1]); break;
                    case "已上市流通市值": investor.OnSellPrice = double.Parse(inputArray[i + 1]); break;
                    case "过户总笔数": investor.transferNum = double.Parse(inputArray[i + 1]); break;
                    case "过户总金额": investor.transferPrice = double.Parse(inputArray[i + 1]); break;
                    case "结算总额": investor.closeAllPrice = double.Parse(inputArray[i + 1]); break;
                    case "结算净额": investor.closeNetPrice = double.Parse(inputArray[i + 1]); break;
                    case "限售流通市值": break;
                    default:break;
                }
            }
            return investor;
        }
        public static async System.Threading.Tasks.Task AutoSaveInvestorsAsync()
        {
            List<Investor> investors = new List<Investor>();
            for (int i = 2005; i <= DateTime.Now.Year; i++)
            {
                for (int j = 01; j <= 12; j++)
                {
                    if(i == DateTime.Now.Year & j == DateTime.Now.Month)
                    {
                        break;
                    }
                    int date = i * 100 + j;
                    var temp = GetInvestorData(date);
                    if (temp != null)
                    {
                        investors.Add(temp);
                    }
                    else
                    {
                        break;
                    }

                }
            }
            await Base.InvestorDatabase.SaveAllInvestorAsync(investors);
        }
    }

}
